<template>
  <div ref="scrollContainer" class="login-page" >
    <img class="background-img"
         src="https://xiaoxiaobaiyang.oss-cn-shenzhen.aliyuncs.com/student_System_img/schoolBackground.jpg"
         alt="背景图">
    <div class="welcome-container">
      <div class="welcome-body">
        <span class="system-title">学生综合服务系统</span>
        <el-button class="enter-button" type="primary" @click="pageDown" plain>登录系统</el-button>
        <i class="el-icon-edit"></i>
        <el-icon :size="40" color="#fff">
         <ArrowDownBold/>
        </el-icon>

      </div>
    </div>
    <div class="login-container">
      <div class="login-box">
        <span class="login-title">用户登录</span>
        <el-form :model="loginFormData" ref="loginFormRef" :rules="loginRules">
          <el-form-item prop="userid" size="large" class="login-item">
            <el-input v-model="loginFormData.userid" placeholder="请输入用户名" :prefix-icon="UserFilled" />
          </el-form-item>
          <el-form-item prop="password"  size="large" class="login-item">
            <el-input v-model="loginFormData.password" type="password" placeholder="请输入密码" :prefix-icon="Lock" />
          </el-form-item>
          <el-form-item size="large" class="login-item">
            <el-button class="login-button" type="primary" @click="submitLoginForm" :loading="buttonLoading">登录</el-button>
          </el-form-item>
          <el-form-item size="default">
            <el-button class="login-button" type="primary" @click="pageDown2" plain>新用户注册</el-button>
          </el-form-item>
        </el-form>
        <div class="page-down-arrow">
          <el-icon :size="40" color="#fff">
            <ArrowDownBold/>
          </el-icon>
        </div>
      </div>
    </div>
    <div class="login-container">
      <div class="register-box">
        <span class="login-title">用户注册</span>
        <el-form :model="registerFormData" ref="registerFormRef" :rules="registerRules">
          <el-form-item prop="userid" size="large" class="login-item">
            <el-input v-model="registerFormData.userid" placeholder="请输入用户名" :prefix-icon="UserFilled" />
          </el-form-item>
          <el-form-item prop="password" size="large" class="login-item">
            <el-input v-model="registerFormData.password" type="password" placeholder="请输入密码" :prefix-icon="Lock" />
          </el-form-item>
          <el-form-item prop="confirmPassword" size="large" class="login-item">
            <el-input v-model="registerFormData.confirmPassword" type="password" placeholder="请确认密码" :prefix-icon="Lock" />
          </el-form-item>
          <el-form-item prop="name" size="large" class="login-item">
            <el-input v-model="registerFormData.name" placeholder="请输入姓名" />
          </el-form-item>


          <el-form-item size="large" class="login-item">
            <el-button class="login-button" type="primary" @click="submitRegisterForm" :loading="buttonLoading">注册</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script setup>
import { onMounted, onUnmounted,reactive, ref } from 'vue';
import {ArrowDownBold} from "@element-plus/icons-vue/global";
import { UserFilled, Lock } from '@element-plus/icons-vue'
import {ElMessage, ElNotification} from 'element-plus';
import { setStorage } from '@/utils/localStorage.js'
import router from '@/router/index.js';
import {loginUser, registerUser} from "@/api/login.js";
/*------------定义变量开始---------------*/
//获取浏览器视口高度
const viewportHeight = ref(900)

//登录表单的数据
const loginFormData = reactive({
  userid: "",
  password: ""
});

//获取登录表单DOM
const loginFormRef = ref(null);
//登录表单规则
const loginRules = {
  userid: [{
    required: true,
    message: '请输入用户名',
    trigger: 'blur'
  }],
  password: [{
    required: true,
    message: '请输入密码',
    trigger: 'blur'
  }],
}
//按钮节流
const buttonLoading = ref(false)

//注册表单数据
const registerFormData = reactive({
  userid: "",
  password: "",
  confirmPassword:"",
  name:"",
  gender:"男",
  role: 3
})
//获取注册表单DOM
const registerFormRef = ref(null);
//注册表单规则
const registerRules = {
  userid: [{
    required: true,
    message: '请输入用户名',
    trigger: 'blur'
  }],
  password: [{
    required: true,
    message: '请输入密码',
    trigger: 'blur'
  }],
  confirmPassword: [{
    required: true,
    message: '请再次输入密码',
    trigger: 'blur'
  }],
  name: [{
    required: true,
    message: '请输入真实姓名',
    trigger: 'blur'
  }],
  gender: [{
    required: true,
    message: '性别不能为空',
    trigger: 'change',
  }],
  role: [{
    required: true,
    message: '请选择角色',
    trigger: 'change'
  }],
}
/*------------定义变量结束---------------*/


/*------------定义监听器开始---------------*/
// 添加滚动事件监听器
onMounted(() => {
  viewportHeight.value =  window.innerHeight;
  window.addEventListener('wheel', handleScroll,{ passive: false });
});
// 移除滚动事件监听器，避免内存泄漏
onUnmounted(() => {
  window.removeEventListener('wheel', handleScroll);
});
/*------------定义监听器结束-------------*/


/*------------定义函数开始---------------*/
// 滚动事件处理器
const handleScroll = (event) => {
  // 阻止默认滚动行为
  event.preventDefault();
  // 根据滚轮的方向决定滚动方向
  const deltaY = event.deltaY;
  let scrollAmount = 0;
  if (deltaY > 0) {
    // 向下滚动
    scrollAmount = viewportHeight.value;
  } else if (deltaY < 0) {
    // 向上滚动
    scrollAmount = -viewportHeight.value;
  }
  // 使用 scrollBy 方法滚动指定的距离
  window.scrollBy({
    top:  scrollAmount,
    behavior: 'smooth' });
};
//翻页函数
const pageDown =() => {
  window.scrollTo({
    top:  viewportHeight.value,
    behavior: 'smooth' });
}
const pageDown2 =() => {
  window.scrollTo({
    top:  2 * viewportHeight.value,
    behavior: 'smooth' });
}

//登录表单验证函数
const submitLoginForm = () => {
  loginFormRef.value.validate((valid) => {
    if (valid) {
      //表单验证通过-请求后台接口进行登录
      login()
    } else {
      //表单验证失败
      ElMessage.error('验证失败');
    }
  })
}

//登录
const login = () => {
  buttonLoading.value = true;
  loginUser(loginFormData).then(res => {
    if (res.status === 200) { //登录成功
      //保存token,用户信息, 用户菜单到浏览器缓存
      setStorage("Token", res.data.token);
      setStorage("userInfo", JSON.stringify(res.data.userInfo));
      setStorage("appEntryList",JSON.stringify(res.data.appEntryList))

      ElNotification.success({
        title: '登录成功',
        message: '欢迎您，' + res.data.userInfo.name + "，您的身份是：" + getRoleString(res.data.userInfo.role),
        type: 'warning',
      })
      //页面跳转
      router.push("/main");
    }
    else if(res.status === 404){
      //登录失败
      ElMessage.error(res.message)
    }
    buttonLoading.value = false;
  }).catch(() => {
    ElMessage.error("用户名或密码错误")
    buttonLoading.value = false;
  })
}

//注册表单验证函数
const submitRegisterForm = () => {
  registerFormRef.value.validate((valid) => {
    if (valid) {
      if(registerFormData.password === registerFormData.confirmPassword){
        //表单验证通过-请求后台接口进行注册
        register();
      }else{
        ElNotification({
          title: '提示',
          message: '两次密码输入不一致',
          type: 'warning',
        })
      }

    } else {
      //表单验证失败
      ElMessage.error("验证失败")
    }
  })
}

//注册
const register = () => {
  buttonLoading.value = true;
  registerUser(registerFormData).then(res => {
    if (res.status === 200) {
      ElNotification.success({
        title: '注册成功',
        message: "用户名：" + res.data.userid + "   姓名：" + res.data.name,
        type: 'success',
      })
      pageDown()
    }
    else{
      ElMessage.error("注册失败")
    }
    buttonLoading.value = false;
  })
}

const getRoleString = (i) => {
  switch (i){
    case 0:
      return "管理员"
    case 1:
      return "领导"
    case 2:
      return "辅导员"
    case 3:
      return "学生"
    default:
      return "新生"
  }
}

/*------------定义函数结束---------------*/
</script>

<style scoped>
.login-page{
  padding: 0;
  margin: 0;
}
.background-img{
  position: fixed;
  z-index: -100;
  padding: 0;
  width: 100%;
  height: 100vh;
}
.welcome-container{
  width: 100%;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}

.welcome-body{
  position: absolute;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
.system-title{
  margin-top: 300px;
  color: white;
  font-size: 60px;
  font-weight: bolder;
  letter-spacing: 3px;
}
.enter-button{
  width: 200px;
  height: 50px;
  font-size: 20px ;
  font-weight: bold;
  margin: 120px;
  background-image: linear-gradient(to top right, #16a2ee, #89d55d);
  color: white;
}
.enter-button:hover{
  width: 200px;
  height: 50px;
  font-size: 20px ;
  font-weight: bold;
  border: none;
  margin: 120px;
  background-image: linear-gradient(to top right, #0b81c0, #44b404);
  color: #b7e4f5;
}
.el-icon-edit{
  width: 100px;
  height: 100px;
}
.login-container{
  width: 100%;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  backdrop-filter: blur(4px);
}
.login-box{
  width: 70vh;
  height: 50vh;
  display: flex;
  margin-top: 100px;
  flex-direction: column;
  justify-content: center;
}
.login-title{
  text-align: center;
  color: white;
  font-size: 30px;
  font-weight: bolder;
  letter-spacing: 10px;
  margin-bottom: 50px;
}
.login-item{
  margin-top: 30px;
  margin-bottom: 30px;
}
.login-button{
  width: 100%;
}
.page-down-arrow{
  margin-top: 150px;
  width: 100%;
  display: flex;
  justify-content: center;
}
.register-box{
  width: 70vh;
  height: 50vh;
  display: flex;
  flex-direction: column;
  justify-content: center;
}
</style>
